package controllers

import (
	"context"
	beego "github.com/beego/beego/v2/server/web"
	"time"
	"xinhua_book/cache"
	"xinhua_book/models"
)

type UserController struct {
	beego.Controller
}

// 用户登录
func (c *UserController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	key := "login_fail" + username
	count, _ := cache.Rdb.Get(context.Background(), key).Int()
	if count > 2 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "账号已被锁定，请两小时后重试",
		}
		c.ServeJSON()
		return
	}

	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户名或密码不能为空",
		}
		c.ServeJSON()
		return
	}

	var user models.User
	err := user.GetInfoByUsername(username)
	if user.ID == 0 {
		cache.Rdb.Incr(context.Background(), key).Result()
		if count == 2 {
			cache.Rdb.Expire(context.Background(), key, time.Hour*2)
		}
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "该用户不存在，登录失败",
		}
		c.ServeJSON()
		return
	}

	if user.Password != password {
		cache.Rdb.Incr(context.Background(), key).Result()
		if count == 2 {
			cache.Rdb.Expire(context.Background(), key, time.Hour*2)
		}
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "密码错误，登录失败",
		}
		c.ServeJSON()
		return
	}
	if err != nil {
		cache.Rdb.Incr(context.Background(), key).Result()
		if count == 2 {
			cache.Rdb.Expire(context.Background(), key, time.Hour*2)
		}
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "登录失败",
		}
		c.ServeJSON()
	} else {
		cache.Rdb.Del(context.Background(), key)
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "登录成功",
		}
		c.ServeJSON()
	}
}
